package com.czr.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.czr.constant.isLogin;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.qcloud.cos.demo.BucketRefererDemo.cosClient;

/**
 * 图片上传、下载
 */
@Slf4j
@Api(value = "图片上传、下载", tags = "图片上传、下载")
@RestController
@RequestMapping("/file")
public class FileController implements Serializable {

    @Value("${imagePath}")
    private String imagePath;
    @Value("${imageZSPath}")
    private String imageZSPath;

    @ApiOperation(value = "图片展示", notes = "图片展示")
    @isLogin
    @GetMapping("/imgFile/{fileName:.+}")
    public void imgFile(HttpServletResponse response, HttpServletRequest request, @PathVariable("fileName") String fileName) throws Exception {
        log.info("fileName->{}", fileName);
        try (FileInputStream inputStream = new FileInputStream(imagePath + fileName)) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inputStream.close();
            byte[] data = outStream.toByteArray();
            response.setContentType("image/jpg");
            OutputStream os = response.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("加载图片失败");
        }
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "图片上传", notes = "图片上传")
    @isLogin
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用uuid重写生成uuid
        String fileName = UUID.randomUUID().toString() + ".jpg";

        //创建一个目录对象
        File dir = new File(imagePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String thumbnailFilePathName = "";
        try {
            thumbnailFilePathName = imagePath + fileName;
            file.transferTo(new File(thumbnailFilePathName));
            commpressPicCycle(thumbnailFilePathName);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok(imageZSPath + fileName);
    }

    public void commpressPicCycle(String thumbnailFilePathName) {
        try {

            for (int i = 0; i < 100; i++) {
                File imgFile = new File(thumbnailFilePathName);
                long fileSize = imgFile.length();
                if (fileSize <= 600 * 1000) {
                    break;
                }
                Thumbnails.of(thumbnailFilePathName).scale(0.9f).outputQuality(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
//
//    /**
//     * 文件下载
//     *
//     * @param name
//     * @param response
//     */
    @ApiOperation(value = "图片下载", notes = "图片下载")
    @isLogin
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        //输入流，通过输入流读取文件内容
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(imagePath + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//
//
//    /**
//     * 文件上传
//     *
//     * @param file
//     * @return
//     */
//    @ApiOperation(value = "图片上传-新", notes = "图片上传-新")
//    @isLogin
//    @PostMapping("/upload")
//    public R<String> upload(MultipartFile file) throws Exception {
//        log.info(file.toString());
//        String secretId = "AKID1vc7uVt3ye6IGzVogKjwwjHbjgR0PbZK";//用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
//        String secretKey = "c3JUXO5bwAByc7PWSBhz4wdCj6KNFuNd";//用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
//
//        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
//        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
//// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
//        Region region = new Region("ap-nanjing");
//        ClientConfig clientConfig = new ClientConfig(region);
//// 这里建议设置使用 https 协议
//// 从 5.6.54 版本开始，默认使用了 https
////clientConfig.setHttpProtocol(HttpProtocol.https);
//        // 3 生成 cos 客户端。
//        COSClient cosClient = new COSClient(cred, clientConfig);
//        //原始文件名
//        String originalFilename = file.getOriginalFilename();
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //使用uuid重写生成uuid
//        String fileName = UUID.randomUUID().toString() + suffix;
//        // 指定要上传的文件
////        File localFile = new File(localFilePath);
//// 指定文件将要存放的存储桶
//        String bucketName = "wenge-test-1252116866";
//
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,fileName, multipartFileToFile(file, fileName));
//
//        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//
////        String path = "https://" + putObjectRequest.getBucketName() + ".cos.ap-nanjing.myqcloud.com/" + fileName;
//        return R.ok(fileName);
//    }

    public File multipartFileToFile(MultipartFile file, String suffix) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(suffix);
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    @isLogin
//    @GetMapping("/imgFile_wx/{fileName:.+}")
//    public String imgFile_wx(HttpServletResponse response, HttpServletRequest request, @PathVariable("fileName") String fileName) throws Exception {
//        String secretId = "AKID1vc7uVt3ye6IGzVogKjwwjHbjgR0PbZK";//用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
//        String secretKey = "c3JUXO5bwAByc7PWSBhz4wdCj6KNFuNd";//用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
//
//        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
//        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
//// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
//        Region region = new Region("ap-nanjing");
//        ClientConfig clientConfig = new ClientConfig(region);
//// 这里建议设置使用 https 协议
//// 从 5.6.54 版本开始，默认使用了 https
////clientConfig.setHttpProtocol(HttpProtocol.https);
//        // 3 生成 cos 客户端。
//        COSClient cosClient = new COSClient(cred, clientConfig);
//        // Bucket 的命名格式为 BucketName-APPID ，此处填写的存储桶名称必须为此格式
//        String bucketName = "wenge-test-1252116866";
//// 设置签名过期时间(可选), 若未进行设置则默认使用 ClientConfig 中的签名过期时间(1小时)
//// 这里设置签名在半个小时后过期
//        Date expirationDate = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
//
//// 填写本次请求的参数，需与实际请求相同，能够防止用户篡改此签名的 HTTP 请求的参数
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("fileName", fileName);
//
//// 填写本次请求的头部，需与实际请求相同，能够防止用户篡改此签名的 HTTP 请求的头部
//        Map<String, String> headers = new HashMap<String, String>();
////        headers.put("header1", "value1");
//
//// 请求的 HTTP 方法，上传请求用 PUT，下载请求用 GET，删除请求用 DELETE
//        HttpMethodName method = HttpMethodName.GET;
//
//        URL url = cosClient.generatePresignedUrl(bucketName, fileName, expirationDate, method, headers, params);
//        System.out.println(url.toString());
//
//// 确认本进程不再使用 cosClient 实例之后，关闭之
//        cosClient.shutdown();
//        return url.toString();
//    }
}
